<template>
  <div class="articles">
    <van-tabs v-model:active="activeTab" sticky>
      <van-tab title="全部">
        <van-sticky offset-top="44">
          <van-dropdown-menu>
            <van-dropdown-item 
              v-model="categoryFilter" 
              :options="categoryOptions" 
            />
            <van-dropdown-item 
              v-model="statusFilter" 
              :options="statusOptions" 
            />
          </van-dropdown-menu>
        </van-sticky>
        
        <van-pull-refresh 
          v-model="refreshing" 
          @refresh="onRefresh"
        >
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <van-cell 
              v-for="article in articles" 
              :key="article.id"
              :title="article.title"
              :label="`${article.category} · ${article.author} · ${article.date}`"
              is-link
              @click="editArticle(article)"
            >
              <template #icon>
                <div class="placeholder-image"></div>
              </template>
              
              <template #right-icon>
                <van-tag :type="article.status === 'published' ? 'success' : 'warning'">
                  {{ article.status === 'published' ? '已发布' : '草稿' }}
                </van-tag>
              </template>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      
      <van-tab title="已发布">
        <van-list
          v-model:loading="loadingPublished"
          :finished="finishedPublished"
          finished-text="没有更多了"
          @load="onLoadPublished"
        >
          <van-cell 
            v-for="article in publishedArticles" 
            :key="article.id"
            :title="article.title"
            :label="`${article.category} · ${article.author} · ${article.date}`"
            is-link
            @click="editArticle(article)"
          >
            <template #icon>
              <div class="placeholder-image"></div>
            </template>
          </van-cell>
        </van-list>
      </van-tab>
      
      <van-tab title="草稿">
        <van-list
          v-model:loading="loadingDrafts"
          :finished="finishedDrafts"
          finished-text="没有更多了"
          @load="onLoadDrafts"
        >
          <van-cell 
            v-for="article in draftArticles" 
            :key="article.id"
            :title="article.title"
            :label="`${article.category} · ${article.author} · ${article.date}`"
            is-link
            @click="editArticle(article)"
          >
            <template #icon>
              <div class="placeholder-image"></div>
            </template>
          </van-cell>
        </van-list>
      </van-tab>
    </van-tabs>
    
    <van-empty 
      v-if="articles.length === 0 && !loading" 
      description="暂无资讯数据" 
    />
    
    <van-button 
      round 
      type="primary" 
      class="add-btn"
      @click="showAddForm = true"
    >
      <van-icon name="plus" /> 添加资讯
    </van-button>
    
    <!-- 添加/编辑表单 -->
    <van-popup 
      v-model:show="showAddForm" 
      position="bottom" 
      :style="{ height: '90%' }"
    >
      <van-form @submit="onSaveArticle">
        <van-nav-bar
          :title="editingArticle ? '编辑资讯' : '添加资讯'"
          left-text="取消"
          right-text="保存"
          @click-left="showAddForm = false"
          @click-right="onSaveArticle"
        />
        
        <div class="form-content">
          <van-cell-group inset>
            <van-field
              v-model="articleForm.title"
              name="标题"
              label="标题"
              placeholder="请输入文章标题"
              :rules="[{ required: true, message: '请输入文章标题' }]"
            />
            
            <van-field
              v-model="articleForm.category"
              name="分类"
              label="分类"
              is-link
              readonly
              placeholder="请选择分类"
              @click="showCategoryPicker = true"
              :rules="[{ required: true, message: '请选择分类' }]"
            />
            
            <van-field
              v-model="articleForm.author"
              name="作者"
              label="作者"
              placeholder="请输入作者姓名"
              :rules="[{ required: true, message: '请输入作者姓名' }]"
            />
            
            <van-field name="uploader" label="封面图">
              <template #input>
                <van-uploader v-model="articleForm.images" :max-count="1" />
              </template>
            </van-field>
            
            <van-field
              v-model="articleForm.summary"
              name="摘要"
              label="摘要"
              type="textarea"
              rows="2"
              autosize
              placeholder="请输入文章摘要"
            />
            
            <van-field
              v-model="articleForm.content"
              name="内容"
              label="内容"
              type="textarea"
              rows="4"
              autosize
              placeholder="请输入文章内容"
              :rules="[{ required: true, message: '请输入文章内容' }]"
            />
            
            <van-field name="switch" label="立即发布">
              <template #input>
                <van-switch v-model="articleForm.published" />
              </template>
            </van-field>
          </van-cell-group>
        </div>
      </van-form>
    </van-popup>
    
    <!-- 分类选择器 -->
    <van-popup v-model:show="showCategoryPicker" round position="bottom">
      <van-picker
        :columns="categories"
        @confirm="onConfirmCategory"
        @cancel="showCategoryPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { showToast } from 'vant'

const activeTab = ref(0)
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const loadingPublished = ref(false)
const finishedPublished = ref(false)
const loadingDrafts = ref(false)
const finishedDrafts = ref(false)

const showAddForm = ref(false)
const showCategoryPicker = ref(false)
const editingArticle = ref(null)

const categoryFilter = ref('all')
const statusFilter = ref('all')

const categoryOptions = [
  { text: '全部分类', value: 'all' },
  { text: '景点推荐', value: 'attraction' },
  { text: '出行攻略', value: 'strategy' },
  { text: '住宿推荐', value: 'accommodation' },
  { text: '美食指南', value: 'food' },
  { text: '交通指南', value: 'transport' }
]

const statusOptions = [
  { text: '全部状态', value: 'all' },
  { text: '已发布', value: 'published' },
  { text: '草稿', value: 'draft' }
]

const categories = [
  { text: '景点推荐', value: 'attraction' },
  { text: '出行攻略', value: 'strategy' },
  { text: '住宿推荐', value: 'accommodation' },
  { text: '美食指南', value: 'food' },
  { text: '交通指南', value: 'transport' }
]

const articles = ref([
  {
    id: 1,
    title: '夏日海滨度假胜地推荐',
    category: '景点推荐',
    author: '旅行达人',
    date: '2023-08-15',
    summary: '为您精选全球最美的海滨度假胜地',
    content: '详细内容...',
    status: 'published'
  },
  {
    id: 2,
    title: '秋季登山装备指南',
    category: '出行攻略',
    author: '户外专家',
    date: '2023-08-12',
    summary: '登山必备装备清单及选购建议',
    content: '详细内容...',
    status: 'published'
  },
  {
    id: 3,
    title: '特色民宿体验分享',
    category: '住宿推荐',
    author: '民宿爱好者',
    date: '2023-08-10',
    summary: '那些让人难忘的特色民宿',
    content: '详细内容...',
    status: 'draft'
  }
])

const publishedArticles = ref([])
const draftArticles = ref([])

const articleForm = reactive({
  title: '',
  category: '',
  author: '',
  images: [],
  summary: '',
  content: '',
  published: false
})

const onRefresh = () => {
  setTimeout(() => {
    refreshing.value = false
    showToast('刷新成功')
  }, 1000)
}

const onLoad = () => {
  setTimeout(() => {
    loading.value = false
    finished.value = true
  }, 1000)
}

const onLoadPublished = () => {
  setTimeout(() => {
    publishedArticles.value = articles.value.filter(article => article.status === 'published')
    loadingPublished.value = false
    finishedPublished.value = true
  }, 1000)
}

const onLoadDrafts = () => {
  setTimeout(() => {
    draftArticles.value = articles.value.filter(article => article.status === 'draft')
    loadingDrafts.value = false
    finishedDrafts.value = true
  }, 1000)
}

const editArticle = (article) => {
  editingArticle.value = article
  Object.assign(articleForm, article)
  showAddForm.value = true
}

const onConfirmCategory = (option) => {
  articleForm.category = option.selectedValues[0]
  showCategoryPicker.value = false
}

const onSaveArticle = () => {
  if (!articleForm.title || !articleForm.category || !articleForm.author || !articleForm.content) {
    showToast('请填写必填项')
    return
  }
  
  const status = articleForm.published ? 'published' : 'draft'
  
  if (editingArticle.value) {
    // 编辑模式
    const index = articles.value.findIndex(item => item.id === editingArticle.value.id)
    if (index !== -1) {
      articles.value[index] = { 
        ...editingArticle.value, 
        ...articleForm,
        status
      }
    }
    showToast('编辑成功')
  } else {
    // 新增模式
    const newArticle = {
      id: Date.now(),
      ...articleForm,
      date: new Date().toISOString().slice(0, 10),
      status
    }
    articles.value.push(newArticle)
    showToast('添加成功')
  }
  
  showAddForm.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(articleForm, {
    title: '',
    category: '',
    author: '',
    images: [],
    summary: '',
    content: '',
    published: false
  })
  editingArticle.value = null
}
</script>

<style scoped>
.articles {
  padding-bottom: 50px;
}

.placeholder-image {
  width: 40px;
  height: 40px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin-right: 10px;
}

.add-btn {
  position: fixed;
  bottom: 70px;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
}

.form-content {
  padding-top: 46px;
}
</style>